package com.tcs.gather.config.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.tcs.gather.commod.ICommodExec;
import com.tcs.gather.config.ConfigModel;
import com.tcs.gather.config.IConfig;
import com.tcs.gather.config.check.ICheckConfig;
import com.tcs.gather.model.CommandModel;
import com.tcs.gather.model.InputAndOutModel;
import com.tcs.gather.model.factory.CommandFactory;
import com.tcs.queue.ISingleionQueue;
import com.tcs.util.system.exception.GatherFileNotExistsException;

/**
 * 配置解析详情
 * 
 * @author wangbo
 */
@Component(value = "config")
public class ConfigImpl implements IConfig {

	private final Logger logger = LoggerFactory.getLogger(ConfigImpl.class);
	
	ExecutorService executor = Executors.newCachedThreadPool();

	@Resource(name = "checkConfig")
	private ICheckConfig checkConfig;
	
	@Resource(name="inputCommodExec")
	private ICommodExec inputCommandExec;
	
	@Resource(name="outputCommodExec")
	private ICommodExec outputCommandExec;
	
	@Resource(name="singleionQueue")
	private ISingleionQueue<String> queue;
	
	@Override
	public InputStream getFile(ConfigModel configModel) {
		InputStream inputStream = null;
		try {
			if (checkConfig.checkFilePath(configModel)) {
				logger.info("config_file : {} " , configModel.getFilePath());
				inputStream = new FileInputStream(configModel.getFilePath());
			}
		} catch (GatherFileNotExistsException e) {
			logger.error("", e);
		} catch (FileNotFoundException e) {
			logger.error("", e);
		}
		return inputStream;
	}

	@Override
	public Properties readFile(InputStream inputStream) {
		Properties prop = new Properties();
		if (null != inputStream) {
			try {
				prop.load(inputStream);
			} catch (IOException e) {
				logger.error("", e);
			}
		}
		return prop;
	}
	
	@Override
	public CommandModel createCommandModel(Properties properties) {
		InputAndOutModel inputAndOutModel = null;
		if (null != properties) {
			inputAndOutModel = CommandFactory.createInputAndOut(properties);
			inputAndOutModel.addCommodExec(inputCommandExec);
			inputAndOutModel.addCommodExec(outputCommandExec);
			logger.info("inputAndOutModel : {} " , inputAndOutModel);
			for (ICommodExec icomodExec : inputAndOutModel.getCommodList()) {
				icomodExec.execCommod(inputAndOutModel,executor,queue);// 执行命令
			}
		}
		return null;
	}
	
	public void setCheckConfig(ICheckConfig checkConfig) {
		this.checkConfig = checkConfig;
	}
}